package jp.co.sharp.android.parents.kidsguard.activity.home;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.design.widget.NavigationView;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.NotificationCompat;
import android.support.v7.widget.Toolbar;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.bluetooth.parentble.ParentBleTransfer;


import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.text.MessageFormat;
import java.util.Iterator;
import java.util.List;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.bluetooth.BluetoothSearchActivity;
import jp.co.sharp.android.parents.kidsguard.activity.common.MimamoriContactAddActivity;
import jp.co.sharp.android.parents.kidsguard.activity.edit.EditActivity;
import jp.co.sharp.android.parents.kidsguard.activity.profile.ProfileEditActivity;
import jp.co.sharp.android.parents.kidsguard.activity.sendImage.PreviewActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.SettingActivity;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.MimamoriConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.MimamoriPhoneDlg;
import jp.co.sharp.android.parents.kidsguard.common.OpenBluetoothConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.PermissionDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessPointDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.activity.mimamori.MimamoriAlertActivity;
import jp.co.sharp.android.parents.kidsguard.contants.MessageConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestCodeConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothItemDto;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.utils.CommonUtils;

public class HomeActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    // みまもり 開始する
    private final static int MIMAMORI_OPEN = 0;
    // みまもり 終了
    private final static int MIMAMORI_CLOSE = 1;
    // みまもり チェック SIM
    private final static int MIMAMORI_CHECK_SIM = 2;
    // みまもり チェック 連絡先
    private final static int MIMAMORI_CHECK_CONTACTS = 3;

    // 接続
    private static final int BTN_CONNECTION_BLUETOOTH = 1;
    // みまもり設定
    private static final int MIMAMORI_CONNECTION_BLUETOOTH = 2;
    // 編集
    private static final int EDIT_CONNECTION_BLUETOOTH = 3;
    // 設定
    private static final int SETTING_CONNECTION_BLUETOOTH = 4;
    // 画像送信
    private static final int SPEAKER_CONNECTION_BLUETOOTH = 5;
    private static final int DISCONNECTION_BLUETOOTH = 6;
    private static final int CONNECTION_BLUETOOTH_FAILED = 7;
    // OPEN みまもり
    private static final int OPEN_MIMAMORI_CONNECTION_BLUETOOTH = 8;
    // Open みまもり Error
    private static final int OPEN_MIMAMORI_ERROR = 9;
    // Open みまもり Success
    private static final int OPEN_MIMAMORI_SUCCESS = 10;
    // Close みまもり Success
    private static final int CLOSE_MIMAMORI_SUCCESS = 11;

    private App mApp;
    private DealWithWaitingDlg mDealWithWaitingDlg;
    private ParentBleTransfer mParentBleTransfer;
    private BluetoothItemDto mBluetoothItemDto;
    // 選択済みmParentBleTransfer

    private KidInfoEntity mKidInfoEntity;
    // 0: 初期化 1: onServiceDiscoveryChanged
    private int mBluetoothFlag = 0;
    // 接続，みまもり設定， 編集， 設定， 画像送信
    private int mBluetoothConnection = 0;
    // 権限CODE
    private final static int ALBUM_PERMISSION_CODE = 1;
    private final static int REQ_PERMISSION_RESULT = 2;
    private long mBackPressed;
    private static final int TIME_EXIT = 2000;
    //
    private boolean mOpenMimamoriWarn = false;
    private boolean mUnReceiver = false;
    // ページジャンプ
    private boolean mPageJumpFlag = false;

    private static final String TAG = "TAG";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "HomeActivity_onCreate");
        setContentView(R.layout.activity_home); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        mApp = (App)getApplication();
        // TODO
//        initReceiver();
        initActivity();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "HomeActivity_onStart");
        initReceiver();
        mUnReceiver = false;
        mApp.setAppStatus(Constants.APP_STATUS_INIT);
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "HomeActivity_onStop");
        if (!mUnReceiver) {
            unregisterReceiver(receiver);
            unregisterReceiver(mimamoriReceiver);
            if (mPageJumpFlag) {
                unregisterReceiver(systemReceiver);
                mPageJumpFlag = false;
            }
            mUnReceiver = true;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "HomeActivity_onDestroy");
        if (!mUnReceiver) {
            unregisterReceiver(receiver);
            unregisterReceiver(mimamoriReceiver);
            if (mPageJumpFlag) {
                unregisterReceiver(systemReceiver);
                mPageJumpFlag = false;
            }
            mUnReceiver = true;
        }
    }

    private void initActivity() {
        Log.i(TAG, "HomeActivity_initActivity");
        Intent intent = getIntent();
        String action = intent.getAction();
        // 追加
        if (null != action && action.equals(Constants.ACTION_ADD_BLUETOOTH)) {
            BluetoothItemDto addBluetoothItemDto = (BluetoothItemDto)intent.getSerializableExtra(Constants.KEY_ADD_BLUETOOTH);
            KidInfoEntity kidInfoEntity = new KidInfoEntity();
            kidInfoEntity.setMacId(addBluetoothItemDto.getMacId());
            kidInfoEntity.setMacAddress(addBluetoothItemDto.getMacAddress());
            kidInfoEntity.setBtConnStatus(Constants.DEVICE_CONNECTION_SUCCESS);
            kidInfoEntity.setSelected(true);
            kidInfoEntity.setControlled(false);
            kidInfoEntity.setKidName(addBluetoothItemDto.getDeviceNickName());
            kidInfoEntity.setBtName(addBluetoothItemDto.getBluetoothName());
            kidInfoEntity.setKidPhoto(addBluetoothItemDto.getKidAvatar());
            kidInfoEntity.setNeverShow(false);

            mApp.insertKidInfo(kidInfoEntity);
            viewDevice(kidInfoEntity);
        // 変更
        } else if (null != action && action.equals(Constants.ACTION_EDIT_BLUETOOTH)) {
            BluetoothItemDto editBluetoothItemDto = (BluetoothItemDto)intent.getSerializableExtra(Constants.KEY_EDIT_BLUETOOTH);
            KidInfoEntity kidInfoEntity = mApp.findKidInfoBySelect();
            kidInfoEntity.setKidName(editBluetoothItemDto.getDeviceNickName());
            kidInfoEntity.setKidPhoto(editBluetoothItemDto.getKidAvatar());
            mApp.updateKidInfo(kidInfoEntity);
            viewDevice(kidInfoEntity);
        // 初期化
        } else if (null != action && action.equals(Constants.ACTION_INIT_HOME)) {
            List<KidInfoEntity> lsKidInfoEntity = mApp.getCacheEntity().getKidLists();
            KidInfoEntity kidInfoEntity = lsKidInfoEntity.get(0);
            kidInfoEntity.setSelected(true);
            kidInfoEntity.setControlled(false);
            kidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
            viewDevice(kidInfoEntity);
            mApp.updateKidInfo(kidInfoEntity);
        } else if (null != action && action.equals(Constants.ACTION_IS_MIMAMORI)) {
            // Mimamori起こる
            isMimamoriChance();
        } else {
            // 以外
            KidInfoEntity kidInfoEntity = mApp.findKidInfoBySelect();
            if (null == kidInfoEntity) {
                List<KidInfoEntity> lsKidInfoEntity = mApp.getCacheEntity().getKidLists();
                kidInfoEntity = lsKidInfoEntity.get(0);
                kidInfoEntity.setSelected(true);
                mApp.updateKidInfo(kidInfoEntity);
            }
            viewDevice(kidInfoEntity);
        }
    }

    /**
     * 初期化Receiver
     */
    private void initReceiver() {
        Log.i(TAG, "HomeActivity_initReceiver");
        IntentFilter filter = new IntentFilter();
        // ロック画面
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        // 画面を開く
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        // 電話ダイヤルブロックの登録
        filter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);

        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_SEARCH);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_SERVICE_DISCOVERY_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        registerReceiver(receiver, filter);
        registerReceiver(mimamoriReceiver, filter);
        registerReceiver(systemReceiver, filter);
        this.mParentBleTransfer = ((App)getApplication()).getmParentBleTransfer();
    }

    @Override
    public void onBackPressed() {
        Log.i(TAG, "HomeActivity_onBackPressed");
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }

        if(mBackPressed + TIME_EXIT > System.currentTimeMillis()){
            super.onBackPressed();
            return;
        }else{
            Toast.makeText(this,"もう一度押すとアプリケーションを終了します",Toast.LENGTH_SHORT).show();
            mBackPressed = System.currentTimeMillis();
        }
    }

    /**
     * デバイス　選択済み
     * @param pKidInfoEntity
     */
    private void viewDevice(KidInfoEntity pKidInfoEntity) {
        Log.i(TAG, "HomeActivity_viewDevice");
        // 選択済み
        this.mKidInfoEntity = pKidInfoEntity;
        TextView deviceName = (TextView)findViewById(R.id.deviceName);
        deviceName.setText(pKidInfoEntity.getKidName());

        TextView deviceStatusMsg = (TextView)findViewById(R.id.deviceStatusMsg);
        Button deviceStatusBtn = (Button)findViewById(R.id.deviceStatusBtn);
        // 接続バテン
        if (Constants.DEVICE_DISCONNECTION_FAILED.equals(pKidInfoEntity.getBtConnStatus())
                || Constants.DEVICE_DISCONNECTION_SUCCESS.equals(pKidInfoEntity.getBtConnStatus())) {
            deviceStatusMsg.setText("キッズケータイ未接続");
            deviceStatusBtn.setText("接続");
            deviceStatusBtn.setTextColor(ResourcesCompat.getColor(getResources(), R.color.colorConnBtn, null));
            deviceStatusBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
        // 接続解除バテン
        } else {
            deviceStatusMsg.setText("キッズケータイ接続済み");
            deviceStatusBtn.setText("接続解除");
            deviceStatusBtn.setTextColor(ResourcesCompat.getColor(getResources(), R.color.colorDisConnBtn, null));
            deviceStatusBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.home_btn_rounded, null));
        }

        ImageView homeKidAvatar = (ImageView)findViewById(R.id.homeKidAvatar);
        if (null != pKidInfoEntity.getKidPhoto()) {
            Uri uri = Uri.fromFile(new File(pKidInfoEntity.getKidPhoto()));
            homeKidAvatar.setImageURI(uri);
        } else {
            homeKidAvatar.setImageResource(R.mipmap.icon_headshot);
        }

        ImageView deviceLeftArrow = (ImageView)findViewById(R.id.deviceLeftArrow);
        ImageView deviceRightArrow = (ImageView)findViewById(R.id.deviceRightArrow);
        if (mApp.getMaxKidInfo() > 1) {
            int currentPosition = mApp.findKidInfoPosition(pKidInfoEntity);
            int maxPosition = mApp.getMaxKidInfo() - 1;
            if (currentPosition == maxPosition) {
                deviceLeftArrow.setVisibility(View.VISIBLE);
                deviceRightArrow.setVisibility(View.INVISIBLE);
            } else if (currentPosition < maxPosition && currentPosition > 0) {
                deviceLeftArrow.setVisibility(View.VISIBLE);
                deviceRightArrow.setVisibility(View.VISIBLE);
            } else if (currentPosition == 0) {
                deviceLeftArrow.setVisibility(View.INVISIBLE);
                deviceRightArrow.setVisibility(View.VISIBLE);
            } else {
                deviceLeftArrow.setVisibility(View.VISIBLE);
                deviceRightArrow.setVisibility(View.VISIBLE);
            }
        } else {
            deviceLeftArrow.setVisibility(View.INVISIBLE);
            deviceRightArrow.setVisibility(View.INVISIBLE);
        }

        deviceStatusBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 接続バテン
                if (Constants.DEVICE_DISCONNECTION_FAILED.equals(pKidInfoEntity.getBtConnStatus())
                        || Constants.DEVICE_DISCONNECTION_SUCCESS.equals(pKidInfoEntity.getBtConnStatus())) {
                    connectDevice(BTN_CONNECTION_BLUETOOTH);
                 // 接続解除バテン
                } else {
                    unConnectDevice();
                }
            }
        });

        deviceLeftArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int currentPosition = mApp.findKidInfoPosition(pKidInfoEntity);
                KidInfoEntity kidInfoEntity = mApp.findKidInfoByPosition(currentPosition - 1);
                pKidInfoEntity.setSelected(false);
                kidInfoEntity.setSelected(true);
                mApp.updateKidInfo(pKidInfoEntity);
                mApp.updateKidInfo(kidInfoEntity);
                viewDevice(kidInfoEntity);
            }
        });

        deviceRightArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int currentPosition = mApp.findKidInfoPosition(pKidInfoEntity);
                KidInfoEntity kidInfoEntity = mApp.findKidInfoByPosition(currentPosition + 1);
                pKidInfoEntity.setSelected(false);
                kidInfoEntity.setSelected(true);
                mApp.updateKidInfo(pKidInfoEntity);
                mApp.updateKidInfo(kidInfoEntity);
                viewDevice(kidInfoEntity);
            }
        });

        // Mimamori
        ImageView imgBtnEditMimamori = (ImageView)findViewById(R.id.imgBtnEditMimamori);
        if (null == mKidInfoEntity || !mKidInfoEntity.getControlled()) {
            imgBtnEditMimamori.setImageResource(R.mipmap.home_mimamori_off);
        } else {
            imgBtnEditMimamori.setImageResource(R.mipmap.home_mimamori_on);
        }
        imgBtnEditMimamori.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null == mKidInfoEntity || !mKidInfoEntity.getControlled()) {
                    mimamoriProcess(MIMAMORI_OPEN);
                } else {
                    mimamoriProcess(MIMAMORI_CLOSE);
                }
            }
        });
    }

    /**
     * デバイス 接続
     * @param pConnectionFlag  接続，みまもり設定， 編集， 設定， 画像送信, OPEN みまもり設定
     */
    private void connectDevice(int pConnectionFlag) {
        Log.i(TAG, "HomeActivity_connectDevice");
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (null != bluetoothAdapter) {
            if (!bluetoothAdapter.isEnabled()) {
                OpenBluetoothConfirmDlg openBluetoothConfirmDlg = new OpenBluetoothConfirmDlg(HomeActivity.this, R.style.commonDlg);
                openBluetoothConfirmDlg.show();
                openBluetoothConfirmDlg.setOnOperateSetListener(new OpenBluetoothConfirmDlg.OnOperateSetListener() {
                    @Override
                    public void onOperateSet() {
                        openBluetoothConfirmDlg.dismiss();
                        startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS)); //直接进入手机中的蓝牙设置界面
                    }
                });
            } else {
                this.mBluetoothConnection = pConnectionFlag;

                String pDlgMsg = "接続中...";
                mDealWithWaitingDlg = new DealWithWaitingDlg(HomeActivity.this, R.style.dealWithWaitingDlg, pDlgMsg, false);
                mDealWithWaitingDlg.show();
                new ConnectBluetoothThread().start();
            }
        }
    }

    /**
     * デバイス 接続解除
     */
    private void unConnectDevice() {
        Log.i(TAG, "HomeActivity_unConnectDevice");
        // Bluetooth確認する
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (null != bluetoothAdapter) {
            if (!bluetoothAdapter.isEnabled()) {
                OpenBluetoothConfirmDlg openBluetoothConfirmDlg = new OpenBluetoothConfirmDlg(HomeActivity.this, R.style.commonDlg);
                openBluetoothConfirmDlg.show();
                openBluetoothConfirmDlg.setOnOperateSetListener(new OpenBluetoothConfirmDlg.OnOperateSetListener() {
                    @Override
                    public void onOperateSet() {
                        openBluetoothConfirmDlg.dismiss();
                        startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS)); //直接进入手机中的蓝牙设置界面
                    }
                });
            } else {
                // Mimamori確認する
                if (mKidInfoEntity.getControlled()) {
                    ProcessWarningDlg processWarningDlg = new ProcessWarningDlg(HomeActivity.this, R.style.commonDlg, MessageConstants.MSG_MIMAMORI_PROCESSING);
                    processWarningDlg.show();
                    processWarningDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                        @Override
                        public void onOperateSet() {
                            processWarningDlg.dismiss();
                        }
                    });
                } else {
                    new DisconnectBluetoothThread().start();
                }
            }
        }
    }

    /**
     * 接続Thread
     */
    private class ConnectBluetoothThread extends Thread {

        @Override
        public void run() {
            try {
                mBluetoothItemDto = new BluetoothItemDto();
                synchronized (mBluetoothItemDto) {
                    mParentBleTransfer.enableScanLeDevice(true);
                    while (null == mBluetoothItemDto.getMacId()) {
                        mBluetoothItemDto.wait(7000L);
                        mParentBleTransfer.enableScanLeDevice(false);
                        if (mBluetoothItemDto.getMacId() == null) {
                            Message msg = new Message();
                            msg.what = CONNECTION_BLUETOOTH_FAILED;
                            handler.sendMessage(msg);
                        }
                        break;
                    }
                    if (null != mBluetoothItemDto.getMacId()) {
                        connectBluetooth(mBluetoothItemDto);
                        mBluetoothItemDto.wait(3000L);
                        if (!Constants.DEVICE_CONNECTION_SUCCESS.equals(mKidInfoEntity.getBtConnStatus())) {
                            Message msg = new Message();
                            msg.what = CONNECTION_BLUETOOTH_FAILED;
                            handler.sendMessage(msg);
                        }
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    }

    /**
     * 接続解除 Thread
     */
    private class DisconnectBluetoothThread extends Thread {
        @Override
        public void run() {
            disconnectBluetooth(mKidInfoEntity);
        }
    }

    /**
     * 接続
     * @param pBluetoothItemDto
     */
    private void connectBluetooth(BluetoothItemDto pBluetoothItemDto) {
        Log.i(TAG, "HomeActivity_connectBluetooth");
        this.mParentBleTransfer.connectLeDevice(pBluetoothItemDto.getMacAddress());
    }

    /**
     * 接続解除
     * @param pKidInfoEntity
     */
    private void disconnectBluetooth(KidInfoEntity pKidInfoEntity) {
        Log.i(TAG, "HomeActivity_disconnectBluetooth");
        this.mParentBleTransfer.disconnectLeDevice(pKidInfoEntity.getMacAddress());
    }

    /*------------------------------------------------------- Mimamori 外で---------------------------------------------------------------------*/
    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                    // ブロードキャストの再登録
                    unregisterReceiver(systemReceiver);
                    initReceiver();
                } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                    mApp.setAppStatus(Constants.APP_STATUS_CLOSE_SYSTEM_DIALOGS);
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    // Bluetoothステータス監視
                    // 初期化
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String macAddress = bluetoothReceiverDto.getAddress();
                    if (bluetoothReceiverDto.getStatus() == Constants.STATUS_BLUETOOTH_CONNECTION) {
                        mBluetoothFlag = Constants.STATUS_BLUETOOTH_CONNECTION;
                    } else if (bluetoothReceiverDto.getStatus() == Constants.STATUS_BLUETOOTH_DISCONNECTION &&
                            bluetoothReceiverDto.getReson() == Constants.REASON_BLUETOOTH_USER_DISCONNECTION) {
                        // Mimamori 起こるかもしれない
                        Message msg = new Message();
                        msg.what = DISCONNECTION_BLUETOOTH;
                        msg.obj = macAddress;
                        handler.sendMessage(msg);
                    }
                } else if (Intent.ACTION_NEW_OUTGOING_CALL.equals(action)) {

                } else {
                    TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);
                    telephonyManager.listen(new PhoneStateListener(){
                        @Override
                        public void onCallStateChanged(int state, String incomingNumber) {
                            super.onCallStateChanged(state, incomingNumber);
//                            Intent freshIntent = new Intent();
                            switch(state){
                                case TelephonyManager.CALL_STATE_IDLE:
//                                    CommonUtils.stopRingtone(null, null);
//                                    CommonUtils.stopVibrator(null);
//                                    freshIntent.setAction("com.android.music.musicservicecommand.pause");
//                                    freshIntent.putExtra("command", "pause");
//                                    sendBroadcast(freshIntent);
                                    break;
                                case TelephonyManager.CALL_STATE_OFFHOOK:
                                    CommonUtils.stopRingtone(null, null);
                                    CommonUtils.stopVibrator(null);
                                    break;
                                case TelephonyManager.CALL_STATE_RINGING:
                                    CommonUtils.stopRingtone(null, null);
                                    CommonUtils.stopVibrator(null);
//                                    freshIntent.setAction("com.android.music.musicservicecommand.pause");
//                                    freshIntent.putExtra("command", "pause");
//                                    sendBroadcast(freshIntent);
                                    break;
                            }
                        }
                    }, PhoneStateListener.LISTEN_CALL_STATE);
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };
    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (RequestReceiverConstants.RECEIVER_BLUETOOTH_SEARCH.equals(action)) {
                    // 从intent中获取设备
                    BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String deviceName = device.getName();
                    String macAddress = device.getAddress();
                    byte[] scanRecord = (byte[]) intent.getByteArrayExtra(RequestReceiverConstants.RECEIVER_MAC_ID_KEY);
                    String scanRecordString = new String(scanRecord).trim();
                    String macId = scanRecordString.substring(scanRecordString.length() - 6, scanRecordString.length());

                    if (null != mKidInfoEntity && macId.equals(mKidInfoEntity.getMacId())) {
                        synchronized (mBluetoothItemDto) {
                            mBluetoothItemDto.setMacId(macId);
                            mBluetoothItemDto.setMacAddress(macAddress);
                            mBluetoothItemDto.setBluetoothName(deviceName);
                            mBluetoothItemDto.notify();
                        }
                    }

                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
//                    // 初期化
//                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
//                    String macAddress = bluetoothReceiverDto.getAddress();
//                    if (bluetoothReceiverDto.getStatus() == Constants.STATUS_BLUETOOTH_CONNECTION) {
//                        mBluetoothFlag = Constants.STATUS_BLUETOOTH_CONNECTION;
//                    } else if (bluetoothReceiverDto.getStatus() == Constants.STATUS_BLUETOOTH_DISCONNECTION &&
//                            bluetoothReceiverDto.getReson() == Constants.REASON_BLUETOOTH_USER_DISCONNECTION) {
//                        // Mimamori 起こるかもしれない
//                        Message msg = new Message();
//                        msg.what = DISCONNECTION_BLUETOOTH;
//                        msg.obj = macAddress;
//                        handler.sendMessage(msg);
//                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_SERVICE_DISCOVERY_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    if (mBluetoothFlag == Constants.STATUS_BLUETOOTH_CONNECTION && bluetoothReceiverDto.isDiscoveryState()) {
                        Message msg = new Message();
                        msg.what = mBluetoothConnection;
                        handler.sendMessage(msg);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (0 == msg.what) {
                if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                    mDealWithWaitingDlg.dismiss();
                }
            } else if (BTN_CONNECTION_BLUETOOTH == msg.what) {
                //接続
                mKidInfoEntity.setMacAddress(mBluetoothItemDto.getMacAddress());
                mKidInfoEntity.setBtConnStatus(Constants.DEVICE_CONNECTION_SUCCESS);
                mKidInfoEntity.setBtName(mBluetoothItemDto.getBluetoothName());
                mApp.updateKidInfo(mKidInfoEntity);
                viewDevice(mKidInfoEntity);
                mDealWithWaitingDlg.dismiss();

                // ウェイクの処理
                synchronized (mBluetoothItemDto) {
                    mBluetoothItemDto.notify();
                }
            } else if (MIMAMORI_CONNECTION_BLUETOOTH == msg.what) {
                // みまもり設定
                mKidInfoEntity.setMacAddress(mBluetoothItemDto.getMacAddress());
                mKidInfoEntity.setBtConnStatus(Constants.DEVICE_CONNECTION_SUCCESS);
                mApp.updateKidInfo(mKidInfoEntity);
                viewDevice(mKidInfoEntity);
                mDealWithWaitingDlg.dismiss();
                showMimamoriActivity(null);

                // ウェイクの処理
                synchronized (mBluetoothItemDto) {
                    mBluetoothItemDto.notify();
                }
            } else if (EDIT_CONNECTION_BLUETOOTH == msg.what) {
                // 編集
                mKidInfoEntity.setMacAddress(mBluetoothItemDto.getMacAddress());
                mKidInfoEntity.setBtConnStatus(Constants.DEVICE_CONNECTION_SUCCESS);
                mApp.updateKidInfo(mKidInfoEntity);
                viewDevice(mKidInfoEntity);
                mDealWithWaitingDlg.dismiss();
                showEditActivity(null);

                // ウェイクの処理
                synchronized (mBluetoothItemDto) {
                    mBluetoothItemDto.notify();
                }
            } else if (SETTING_CONNECTION_BLUETOOTH == msg.what) {
                // 設定
                mKidInfoEntity.setMacAddress(mBluetoothItemDto.getMacAddress());
                mKidInfoEntity.setBtConnStatus(Constants.DEVICE_CONNECTION_SUCCESS);
                mApp.updateKidInfo(mKidInfoEntity);
                viewDevice(mKidInfoEntity);
                mDealWithWaitingDlg.dismiss();
                showSettingActivity(null);

                // ウェイクの処理
                synchronized (mBluetoothItemDto) {
                    mBluetoothItemDto.notify();
                }
            } else if (SPEAKER_CONNECTION_BLUETOOTH == msg.what) {
                // 画像送信
                mKidInfoEntity.setMacAddress(mBluetoothItemDto.getMacAddress());
                mKidInfoEntity.setBtConnStatus(Constants.DEVICE_CONNECTION_SUCCESS);
                mApp.updateKidInfo(mKidInfoEntity);
                viewDevice(mKidInfoEntity);
                mDealWithWaitingDlg.dismiss();
                showSpeakerActivity(null);

                // ウェイクの処理
                synchronized (mBluetoothItemDto) {
                    mBluetoothItemDto.notify();
                }
            } else if (DISCONNECTION_BLUETOOTH == msg.what) {
                //
                KidInfoEntity kidInfoEntity = mApp.findKidInfoByMacAddress((String) msg.obj);
                if (null != kidInfoEntity) {
                    if (kidInfoEntity.getMacId().equals(mKidInfoEntity.getMacId())) {
                        mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                    }
                    kidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                    mApp.updateKidInfo(mKidInfoEntity);
                    viewDevice(mKidInfoEntity);
                }
                // TODO Mimamori
                if (null != kidInfoEntity && mKidInfoEntity.getControlled()) {
                    mApp.addmLsIsMimamori((String) msg.obj);
                    isMimamoriChance();
                }
            } else if (CONNECTION_BLUETOOTH_FAILED == msg.what) {
                mDealWithWaitingDlg.dismiss();
                if (mKidInfoEntity.getControlled()) {
                    //
                    ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(
                            HomeActivity.this,
                            R.style.commonDlg,
                            MessageFormat.format(MessageConstants.MSG_MIMAMORI_CONNECTION_ERROR, mKidInfoEntity.getKidName()));
                    processWarringDlg.show();
                    processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                        @Override
                        public void onOperateSet() {
                            processWarringDlg.dismiss();
                            // TODO
                            mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                            mKidInfoEntity.setControlled(false);
                            mApp.updateKidInfo(mKidInfoEntity);
                            viewDevice(mKidInfoEntity);
                        }
                    });
                } else {
                    String message = mKidInfoEntity.getKidName() + "に接続できませんでした";

                    ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(HomeActivity.this, R.style.commonDlg, message);
                    processWarringDlg.show();
                    processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                        @Override
                        public void onOperateSet() {
                            processWarringDlg.dismiss();
                        }
                    });
                }
            } else if (OPEN_MIMAMORI_CONNECTION_BLUETOOTH == msg.what) {
                // Open みまもり設定
                mKidInfoEntity.setMacAddress(mBluetoothItemDto.getMacAddress());
                mKidInfoEntity.setBtConnStatus(Constants.DEVICE_CONNECTION_SUCCESS);
                mApp.updateKidInfo(mKidInfoEntity);
                viewDevice(mKidInfoEntity);
                mDealWithWaitingDlg.dismiss();
                mimamoriProcess(MIMAMORI_OPEN);

                // ウェイクの処理mDealWithWaitingDlg
                synchronized (mBluetoothItemDto) {
                    mBluetoothItemDto.notify();
                }
            }
        }
    };

    /*------------------------------------------------------- ページ移行 ---------------------------------------------------------------------*/
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        Log.i(TAG, "HomeActivity_onNavigationItemSelected");
        int id = item.getItemId();
        // キッズケータイの追加/削除
        if (id == R.id.leftMenuKid) {
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (null != bluetoothAdapter) {
                if (!bluetoothAdapter.isEnabled()) {
                    OpenBluetoothConfirmDlg openBluetoothConfirmDlg = new OpenBluetoothConfirmDlg(HomeActivity.this, R.style.commonDlg);
                    openBluetoothConfirmDlg.show();
                    openBluetoothConfirmDlg.setOnOperateSetListener(new OpenBluetoothConfirmDlg.OnOperateSetListener() {
                        @Override
                        public void onOperateSet() {
                            openBluetoothConfirmDlg.dismiss();
                            startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS)); //直接进入手机中的蓝牙设置界面
                        }
                    });
                } else {
                    // ページジャンプ
                    mPageJumpFlag = true;
                    Intent intent = new Intent();
                    intent.setAction(Constants.ACTION_KID_BLUETOOTH);
                    intent.setClass(HomeActivity.this, BluetoothSearchActivity.class);
                    startActivity(intent);
                }
            }
            return true;
        }
        // ご利用上の注意
        else if (id == R.id.leftMenuNote) {
            Uri uri = Uri.parse("https://3sh.jp/cp/kids_con/note/");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
            return true;
        }
        // 本アプリの使い方について
        else if (id == R.id.leftMenuAppUse) {
            Uri uri = Uri.parse("https://3sh.jp/cp/kids_con/guide/");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
            return true;
        }
        // オープンソースライセンス
        else if (id == R.id.leftMenuLicense) {
            Intent intent = new Intent();
            intent.setClass(HomeActivity.this, SourceLicenseActivity.class);
            startActivity(intent);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    /**
     * Show Profile
     * @param view
     */
    public void showProfileActivity(View view) {
        Log.i(TAG, "HomeActivity_showProfileActivity");
        // ページジャンプ
        mPageJumpFlag = true;
        Intent intent = new Intent();
        intent.setClass(this, ProfileEditActivity.class);
        intent.setAction(Constants.ACTION_EDIT_BLUETOOTH);
        BluetoothItemDto bluetoothItemDto = new BluetoothItemDto();
        bluetoothItemDto.setMacId(mKidInfoEntity.getMacId());
        bluetoothItemDto.setDeviceNickName(mKidInfoEntity.getKidName());
        bluetoothItemDto.setBluetoothName(mKidInfoEntity.getBtName());
        bluetoothItemDto.setKidAvatar(mKidInfoEntity.getKidPhoto());
        intent.putExtra(Constants.KEY_EDIT_BLUETOOTH, bluetoothItemDto);
        startActivity(intent);
    }

    /**
     * Show Setting
     * @param view
     */
    public void showSettingActivity(View view) {
        Log.i(TAG, "HomeActivity_showSettingActivity");
        // 接続バテン
        if (Constants.DEVICE_DISCONNECTION_FAILED.equals(mKidInfoEntity.getBtConnStatus())
                || Constants.DEVICE_DISCONNECTION_SUCCESS.equals(mKidInfoEntity.getBtConnStatus())) {
            connectDevice(SETTING_CONNECTION_BLUETOOTH);
            return;
        }

        // Mimamori確認する
        if (mKidInfoEntity.getControlled()) {
            ProcessWarningDlg processWarningDlg = new ProcessWarningDlg(HomeActivity.this, R.style.commonDlg, MessageConstants.MSG_MIMAMORI_PROCESSING);
            processWarningDlg.show();
            processWarningDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                @Override
                public void onOperateSet() {
                    processWarningDlg.dismiss();
                }
            });
        } else if (mKidInfoEntity.getNeverShow()) {
            // ページジャンプ
            mPageJumpFlag = true;
            Intent intent = new Intent();
            intent.setClass(this, SettingActivity.class);
            startActivity(intent);
        } else {
            ProcessPointDlg processPointDlg = new ProcessPointDlg(HomeActivity.this, R.style.commonDlg, MessageConstants.MSG_EDIT_SETTING);
            processPointDlg.show();
            processPointDlg.setOnOperateSetListener(new ProcessPointDlg.OnOperateSetListener() {
                @Override
                public void onOperateSet(boolean cbViewDlg) {
                    if (cbViewDlg) {
                        mKidInfoEntity.setNeverShow(true);
                        mApp.updateKidInfo(mKidInfoEntity);
                    }
                    processPointDlg.dismiss();
                    // ページジャンプ
                    mPageJumpFlag = true;
                    Intent intent = new Intent();
                    intent.setClass(HomeActivity.this, SettingActivity.class);
                    startActivity(intent);
                }
            });
        }
    }

    /**
     * Show Edit
     * @param view
     */
    public void showEditActivity(View view) {
        Log.i(TAG, "HomeActivity_showEditActivity");
        // 接続バテン
        if (Constants.DEVICE_DISCONNECTION_FAILED.equals(mKidInfoEntity.getBtConnStatus())
                || Constants.DEVICE_DISCONNECTION_SUCCESS.equals(mKidInfoEntity.getBtConnStatus())) {
            connectDevice(EDIT_CONNECTION_BLUETOOTH);
            return;
        }

        // Mimamori確認する
        if (mKidInfoEntity.getControlled()) {
            ProcessWarningDlg processWarningDlg = new ProcessWarningDlg(HomeActivity.this, R.style.commonDlg, MessageConstants.MSG_MIMAMORI_PROCESSING);
            processWarningDlg.show();
            processWarningDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                @Override
                public void onOperateSet() {
                    processWarningDlg.dismiss();
                }
            });
        } else if (mKidInfoEntity.getNeverShow()) {
            // ページジャンプ
            mPageJumpFlag = true;
            Intent intent = new Intent();
            intent.setClass(this, EditActivity.class);
            startActivity(intent);
        } else {
            ProcessPointDlg processPointDlg = new ProcessPointDlg(HomeActivity.this, R.style.commonDlg, MessageConstants.MSG_EDIT_SETTING);
            processPointDlg.show();
            processPointDlg.setOnOperateSetListener(new ProcessPointDlg.OnOperateSetListener() {
                @Override
                public void onOperateSet(boolean cbViewDlg) {
                    if (cbViewDlg) {
                        mKidInfoEntity.setNeverShow(true);
                        mApp.updateKidInfo(mKidInfoEntity);
                    }
                    processPointDlg.dismiss();
                    // ページジャンプ
                    mPageJumpFlag = true;
                    Intent intent = new Intent();
                    intent.setClass(HomeActivity.this, EditActivity.class);
                    startActivity(intent);
                }
            });
        }
    }

    /**
     * Show Mimamori
     * @param view
     */
    public void showMimamoriActivity(View view) {
        Log.i(TAG, "HomeActivity_showMimamoriActivity");
        // 接続バテン
        if (Constants.DEVICE_DISCONNECTION_FAILED.equals(mKidInfoEntity.getBtConnStatus())
                || Constants.DEVICE_DISCONNECTION_SUCCESS.equals(mKidInfoEntity.getBtConnStatus())) {
            connectDevice(MIMAMORI_CONNECTION_BLUETOOTH);
            return;
        }

        // Mimamori確認する
        if (mKidInfoEntity.getControlled()) {
            ProcessWarningDlg processWarningDlg = new ProcessWarningDlg(HomeActivity.this, R.style.commonDlg, MessageConstants.MSG_MIMAMORI_PROCESSING);
            processWarningDlg.show();
            processWarningDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                @Override
                public void onOperateSet() {
                    processWarningDlg.dismiss();
                }
            });
        } else {
            // ページジャンプ
            mPageJumpFlag = true;
            Intent intent = new Intent();
            intent.setClass(this, MimamoriAlertActivity.class);
            startActivity(intent);
        }
    }

    /**
     * Show Speaker
     * @param view
     */
    public void showSpeakerActivity(View view) {
        Log.i(TAG, "HomeActivity_showSpeakerActivity");
        // 接続バテン
        if (Constants.DEVICE_DISCONNECTION_FAILED.equals(mKidInfoEntity.getBtConnStatus())
                || Constants.DEVICE_DISCONNECTION_SUCCESS.equals(mKidInfoEntity.getBtConnStatus())) {
            connectDevice(SPEAKER_CONNECTION_BLUETOOTH);
            return;
        }

        // Mimamori確認する
        if (mKidInfoEntity.getControlled()) {
            ProcessWarningDlg processWarningDlg = new ProcessWarningDlg(HomeActivity.this, R.style.commonDlg, MessageConstants.MSG_MIMAMORI_PROCESSING);
            processWarningDlg.show();
            processWarningDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                @Override
                public void onOperateSet() {
                    processWarningDlg.dismiss();
                }
            });
        } else if (mKidInfoEntity.getNeverShow()) {
            // ページジャンプ
            mPageJumpFlag = true;

            Intent intent = new Intent();
            intent.setClass(this, PreviewActivity.class);
            startActivity(intent);
        } else {
            ProcessPointDlg processPointDlg = new ProcessPointDlg(HomeActivity.this, R.style.commonDlg, MessageConstants.MSG_EDIT_SETTING);
            processPointDlg.show();
            processPointDlg.setOnOperateSetListener(new ProcessPointDlg.OnOperateSetListener() {
                @Override
                public void onOperateSet(boolean cbViewDlg) {
                    if (cbViewDlg) {
                        mKidInfoEntity.setNeverShow(true);
                        mApp.updateKidInfo(mKidInfoEntity);
                    }
                    processPointDlg.dismiss();
                    // 権限
                    initPermissions();
                }
            });
        }
    }

    /*------------------------------------------------------- 権限 ---------------------------------------------------------------------*/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        Log.i(TAG, "HomeActivity_onActivityResult");
        if (requestCode == REQ_PERMISSION_RESULT) {
            initPermissions();
        } else if (requestCode == RequestCodeConstants.MIMAMORI_CONTACT_ADD) {
            // Mimamori Add Contact
            mOpenMimamoriWarn = true;
            mimamoriProcess(MIMAMORI_OPEN);
        }
    }

    /**
     * 権限を確認してください
     */
    @TargetApi(Build.VERSION_CODES.M)
    private void initPermissions() {
        Log.i(TAG, "HomeActivity_initPermissions");
        // Android バージョン番号
        int version = android.os.Build.VERSION.SDK_INT;
        if (version >= 23) {
            // Album
            if ((checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) ||
                    (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
                requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE}, ALBUM_PERMISSION_CODE);
            } else {
                Intent intent = new Intent();
                intent.setClass(HomeActivity.this, PreviewActivity.class);
                startActivity(intent);
            }
        } else {
            Intent intent = new Intent();
            intent.setClass(HomeActivity.this, PreviewActivity.class);
            startActivity(intent);
        }
    }

    /**
     * 権限を確認してください
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.i(TAG, "HomeActivity_onRequestPermissionsResult");
        Boolean phonePermissionFlag = false;
        Boolean storagePermissionFlag = false;
        if (requestCode == this.ALBUM_PERMISSION_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                phonePermissionFlag = true;
            } else {
                if (shouldShowRequestPermissionRationale(permissions[0])){
                    Toast.makeText(this, "Media Storageの権限が必要です。アクセス権限を付与してください", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:jp.co.sharp.android.parents.kidsguard"));
                    PermissionDlg permissionDlg = new PermissionDlg(HomeActivity.this, R.style.commonDlg);
                    permissionDlg.show();
                    permissionDlg.setOnOperateSetListener(new PermissionDlg.OnOperateSetListener() {
                        @Override
                        public void onOperateSet() {
                            startActivityForResult(intent,1000);
                        }
                    });
                }
            }
            if (grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                storagePermissionFlag = true;
            } else {
                if (shouldShowRequestPermissionRationale(permissions[1])){
                    Toast.makeText(this, "Media Storageの権限が必要です。アクセス権限を付与してください", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:jp.co.sharp.android.parents.kidsguard"));
                    PermissionDlg permissionDlg = new PermissionDlg(HomeActivity.this, R.style.commonDlg);
                    permissionDlg.show();
                    permissionDlg.setOnOperateSetListener(new PermissionDlg.OnOperateSetListener() {
                        @Override
                        public void onOperateSet() {
                            permissionDlg.dismiss();
                            startActivityForResult(intent, REQ_PERMISSION_RESULT);
                        }
                    });
                }
            }
        }
        if(storagePermissionFlag && phonePermissionFlag) {
            Intent intent = new Intent();
            intent.setClass(HomeActivity.this, PreviewActivity.class);
            startActivity(intent);
        }
    }

    /*------------------------------------------------------- Mimamori TODO---------------------------------------------------------------------*/
    /**
     * Mimamori
     * @param pMimamoriStep 0:みまもり 開始する 1:みまもり 終了
     */
    private void mimamoriProcess(int pMimamoriStep) {
        Log.i(TAG, "HomeActivity_mimamoriProcess");
        // 開く
        if(pMimamoriStep == MIMAMORI_OPEN) {
            // 接続バテン
            if (Constants.DEVICE_DISCONNECTION_FAILED.equals(mKidInfoEntity.getBtConnStatus())
                    || Constants.DEVICE_DISCONNECTION_SUCCESS.equals(mKidInfoEntity.getBtConnStatus())) {
                connectDevice(OPEN_MIMAMORI_CONNECTION_BLUETOOTH);
                return;
            }

            if (mKidInfoEntity.getNeverShow() || mOpenMimamoriWarn) {
                mOpenMimamoriWarn = false;
                String pDlgMsg = "起動中...";
                mDealWithWaitingDlg = new DealWithWaitingDlg(HomeActivity.this, R.style.dealWithWaitingDlg, pDlgMsg, false);
                mDealWithWaitingDlg.show();
                new MimamoriThread(MIMAMORI_CHECK_CONTACTS).start();
            } else {
                ProcessPointDlg processPointDlg = new ProcessPointDlg(HomeActivity.this, R.style.commonDlg, MessageConstants.MSG_MIMAMORI);
                processPointDlg.show();
                processPointDlg.setOnOperateSetListener(new ProcessPointDlg.OnOperateSetListener() {
                    @Override
                    public void onOperateSet(boolean cbViewDlg) {
                        if (cbViewDlg) {
                            mKidInfoEntity.setNeverShow(true);
                            mApp.updateKidInfo(mKidInfoEntity);
                        }
                        processPointDlg.dismiss();

                        String pDlgMsg = "起動中...";
                        mDealWithWaitingDlg = new DealWithWaitingDlg(HomeActivity.this, R.style.dealWithWaitingDlg, pDlgMsg, false);
                        mDealWithWaitingDlg.show();
                        new MimamoriThread(MIMAMORI_CHECK_CONTACTS).start();;
                    }
                });
            }
        // 閉じる
        } else if (pMimamoriStep == MIMAMORI_CLOSE) {
            new MimamoriThread(MIMAMORI_CLOSE).start();
        }

    }

    /**
     * Mimamori 設定　自分の電話番号チェック
     */
    private void mimamoriPhoneNumCheck() {
        Log.i(TAG, "HomeActivity_mimamoriPhoneNumCheck");
        if (null == mKidInfoEntity.getParentTel() || "".equals(mKidInfoEntity.getParentTel())) {
            if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                mDealWithWaitingDlg.dismiss();
            }
            ProcessWarningDlg processWarningDlg = new ProcessWarningDlg(HomeActivity.this, R.style.commonDlg, MessageConstants.MSG_CHECK_PHONE_NUM_NONE);
            processWarningDlg.show();
            processWarningDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                @Override
                public void onOperateSet() {
                    processWarningDlg.dismiss();
                }
            });
        } else {
            new MimamoriThread(MIMAMORI_OPEN).start();
        }
    }

    /**
     * Mimamori Thread
     */
    private class MimamoriThread extends Thread {
        private int mMimamoriStep;
        public MimamoriThread(int pMimamoriStep) {
            this.mMimamoriStep = pMimamoriStep;
        }

        @Override
        public void run() {
            switch (mMimamoriStep) {
                case MIMAMORI_OPEN:
                    try {
                        mBluetoothItemDto = new BluetoothItemDto();
                        synchronized (mBluetoothItemDto) {
                            openMimamori();
                            while (!mBluetoothItemDto.isMimamoriState()) {
                                mBluetoothItemDto.wait(10000L);
                                if (!mBluetoothItemDto.isMimamoriState()) {
                                    Message msg = new Message();
                                    msg.what = OPEN_MIMAMORI_ERROR;
                                    mimamoriHandler.sendMessage(msg);
                                }
                                break;
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case MIMAMORI_CLOSE:
                    closeMimamori();
                    break;
                case MIMAMORI_CHECK_SIM:
                    kidSimCardCheck();
                    break;
                case MIMAMORI_CHECK_CONTACTS:
                    kidContactsCheck();
                    break;
            }
        }
    }

    /**
     * Mimamori キッズケータイの電話番号チェック
     */
    private void kidSimCardCheck() {
        Log.i(TAG, "HomeActivity_kidSimCardCheck");
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", RequestMethodConstants.METHOD_ISDOCOMO_SIM_CARD_INSERT);
            jsonObject.put("data", JSONObject.NULL);

            this.mParentBleTransfer.writeLeData(mKidInfoEntity.getMacAddress(), jsonObject.toString());
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    /**
     * Mimamori お使いのスマートフォンの電話番号がキッズケータイに登録されていません。
     */
    private void kidContactsCheck() {
        Log.i(TAG, "HomeActivity_kidContactsCheck");
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", RequestMethodConstants.METHOD_GET_CONTACTS);
            jsonObject.put("data", JSONObject.NULL);

            this.mParentBleTransfer.writeLeData(mKidInfoEntity.getMacAddress(), jsonObject.toString());
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }
    /**
     * Mimamori 開く
     */
    private void openMimamori() {
        Log.i(TAG, "HomeActivity_openMimamori");
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", RequestMethodConstants.METHOD_SET_MIMAMORI_STATE);
            JSONObject jsonData = new JSONObject();
            jsonData.put("state", 0);
            jsonData.put("phone", mKidInfoEntity.getParentTel());
            jsonObject.put("data", jsonData);

            this.mParentBleTransfer.writeLeData(mKidInfoEntity.getMacAddress(), jsonObject.toString());
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    /**
     * Mimamori 閉じる
     */
    private void closeMimamori() {
        Log.i(TAG, "HomeActivity_closeMimamori");
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", RequestMethodConstants.METHOD_SET_MIMAMORI_STATE);
            JSONObject jsonData = new JSONObject();
            jsonData.put("state", 1);
            jsonData.put("phone", mKidInfoEntity.getParentTel());
            jsonObject.put("data", jsonData);

            this.mParentBleTransfer.writeLeData(mKidInfoEntity.getMacAddress(), jsonObject.toString());
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver mimamoriReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    if (bluetoothReceiverDto.isFinished()) {

                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String retStr = bluetoothReceiverDto.getRetStr();
                    JSONObject jsonObject = new JSONObject(retStr);
                    if (RequestMethodConstants.METHOD_ON_SYNC_RESULT.equals(jsonObject.getString("method"))) {
                        if (jsonObject.getString("result").equals(Constants.ON_SYNC_RESULT)) {
                            Message msg = new Message();
                            msg.what = CLOSE_MIMAMORI_SUCCESS;
                            mimamoriHandler.sendMessage(msg);
                        }
                    } else  if (RequestMethodConstants.METHOD_ON_GET_KID_PHONE.equals(jsonObject.getString("method"))) {
                        JSONObject jsonData = jsonObject.getJSONObject("data");
                        mBluetoothItemDto.setMimamoriState(true);
                        mBluetoothItemDto.setKidPhone(jsonData.getString("phone"));

                        Message msg = new Message();
                        msg.what = OPEN_MIMAMORI_SUCCESS;
                        mimamoriHandler.sendMessage(msg);
                    } else if (RequestMethodConstants.METHOD_GET_CONTACTS.equals(jsonObject.getString("method"))) {
                        if (jsonObject.isNull("data")) {
                            Message msg = new Message();
                            msg.what = MIMAMORI_CHECK_CONTACTS;
                            mimamoriHandler.sendMessage(msg);
                        } else {
                            JSONArray jsonArray = jsonObject.getJSONArray("data");
                            if (null != jsonArray && jsonArray.length() > 0) {
                                boolean exist = false;
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject jsonItem = jsonArray.getJSONObject(i);
                                    if (jsonItem.getString("phone").equals(mKidInfoEntity.getParentTel())) {
                                        exist = true;
                                        break;
                                    }
                                }
                                if (!exist) {
                                    Message msg = new Message();
                                    msg.what = MIMAMORI_CHECK_CONTACTS;
                                    mimamoriHandler.sendMessage(msg);
                                } else {
                                    new MimamoriThread(MIMAMORI_CHECK_SIM).start();
                                }
                            } else {
                                Message msg = new Message();
                                msg.what = MIMAMORI_CHECK_CONTACTS;
                                mimamoriHandler.sendMessage(msg);
                            }
                        }
                    } else if (RequestMethodConstants.METHOD_ISDOCOMO_SIM_CARD_INSERT.equals(jsonObject.getString("method"))) {
                        JSONObject jsonData = jsonObject.getJSONObject("data");
                        if (jsonData.getInt("state") == 0) {
                            mimamoriPhoneNumCheck();
                        } else {
                            Message msg = new Message();
                            msg.what = MIMAMORI_CHECK_SIM;
                            mimamoriHandler.sendMessage(msg);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    Handler mimamoriHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (OPEN_MIMAMORI_ERROR == msg.what) {
                // Open みまもり Error
                if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                    mDealWithWaitingDlg.dismiss();
                }
                ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(HomeActivity.this, R.style.commonDlg, MessageConstants.MSG_MIMAMORI_OPEN_ERROR);
                processWarringDlg.show();
                processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                    @Override
                    public void onOperateSet() {
                        processWarringDlg.dismiss();
                    }
                });
            } else if (OPEN_MIMAMORI_SUCCESS == msg.what) {
                // Open みまもり Success
                mKidInfoEntity.setControlled(true);
                mKidInfoEntity.setKidTel(mBluetoothItemDto.getKidPhone());
                mApp.updateKidInfo(mKidInfoEntity);
                viewDevice(mKidInfoEntity);
                if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                    mDealWithWaitingDlg.dismiss();
                }

                // ウェイクの処理
                synchronized (mBluetoothItemDto) {
                    mBluetoothItemDto.notify();
                }
            } else if (CLOSE_MIMAMORI_SUCCESS == msg.what) {
                // Close みまもり Success
                mKidInfoEntity.setControlled(false);
                mApp.updateKidInfo(mKidInfoEntity);
                viewDevice(mKidInfoEntity);
                if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                    mDealWithWaitingDlg.dismiss();
                }
            } else if (MIMAMORI_CHECK_SIM == msg.what) {
                // Open みまもり Error
                if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                    mDealWithWaitingDlg.dismiss();
                }

                ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(HomeActivity.this, R.style.commonDlg, MessageConstants.MSG_CHECK_SIM_CARD_ERROR);
                processWarringDlg.show();
                processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                    @Override
                    public void onOperateSet() {
                        processWarringDlg.dismiss();
                    }
                });
            } else if (MIMAMORI_CHECK_CONTACTS == msg.what) {
                // Open みまもり Error
                if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                    mDealWithWaitingDlg.dismiss();
                }
                Intent intent = new Intent();
                MimamoriConfirmDlg mimamoriConfirmDlg = new MimamoriConfirmDlg(
                        HomeActivity.this,
                        R.style.commonDlg,
                        MessageConstants.MSG_CHECK_CONTACTS_ERROR,
                        MessageConstants.MSG_CHECK_CONTACTS_ERROR_CONFIRM,
                        MessageConstants.MSG_CHECK_CONTACTS_ERROR_CANCEL,
                        null);
                mimamoriConfirmDlg.show();
                mimamoriConfirmDlg.setOnConfirmSetListener(new MimamoriConfirmDlg.OnConfirmSetListener() {
                    @Override
                    public void onOperateSet(String pMacId) {
                        mimamoriConfirmDlg.dismiss();
                        // ページジャンプ
                        mPageJumpFlag = true;
                        intent.setClass(HomeActivity.this, MimamoriContactAddActivity.class);
                        startActivityForResult(intent, RequestCodeConstants.MIMAMORI_CONTACT_ADD);
                    }
                });
                mimamoriConfirmDlg.setOnCancelSetListener(new MimamoriConfirmDlg.OnCancelSetListener() {
                    @Override
                    public void onOperateSet(String pMacId) {
                        mimamoriConfirmDlg.dismiss();
                    }
                });
            }
        }
    };

    /**
     * Mimamori 起こる
     */
    private void isMimamoriChance() {
        Log.i(TAG, "HomeActivity_isMimamoriChance");
        List<String> lsIsMimamori = mApp.getmLsIsMimamori();
        // Mimamori Kid
        if (lsIsMimamori.isEmpty()) {
            return;
        }
        String isMimamoriAdr = lsIsMimamori.get(lsIsMimamori.size() - 1);
        Iterator<String> iterator = lsIsMimamori.iterator();
        while(iterator.hasNext()){
            String item = (String)iterator.next();
            if(isMimamoriAdr.equals(item)){
                iterator.remove();
            }
        }
        // 最初に選択したデバイスをキャンセルする
        KidInfoEntity oldKidInfoEntity = mApp.findKidInfoBySelect();
        oldKidInfoEntity.setSelected(false);
        mApp.updateKidInfo(oldKidInfoEntity);
        // 新しく選択したデバイスを設定します
        KidInfoEntity kidInfoEntity = mApp.findKidInfoByMacAddress(isMimamoriAdr);
        kidInfoEntity.setSelected(true);
        mApp.updateKidInfo(kidInfoEntity);
        //
        mKidInfoEntity = kidInfoEntity;
        viewDevice(kidInfoEntity);

        // 通知音
        if (kidInfoEntity.getRingToneSwitch()) {
            CommonUtils.playRingtone(HomeActivity.this, kidInfoEntity.getRingToneUrl());
        }
        // バイブレーション
        if (kidInfoEntity.getShockSwitch()) {
            CommonUtils.playVibrator(HomeActivity.this);
        }

        // 緊急ポップアップ通知
        if (mApp.getAppStatus() != Constants.APP_STATUS_INIT) {
            int channelId = mApp.findKidInfoPosition(kidInfoEntity);
            NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
            notificationManager.cancel(channelId);
            Intent intent = new Intent(getIntent());
            PendingIntent pendingIntent = PendingIntent.getActivity(HomeActivity.this,0,intent,0);
            if(Build.VERSION.SDK_INT >= 26)
            {
                //当sdk版本大于26
                String description = "ParentApp";
                int importance = NotificationManager.IMPORTANCE_HIGH;
                NotificationChannel channel = new NotificationChannel(String.valueOf(channelId), description, importance);
                notificationManager.createNotificationChannel(channel);
                Notification notification = new Notification.Builder(HomeActivity.this, String.valueOf(channelId))
                        .setCategory(Notification.CATEGORY_MESSAGE)
                        .setSmallIcon(R.mipmap.parent_app_icon)
                        .setContentText(MessageFormat.format("{0}とはぐれました。至急確認してください！", kidInfoEntity.getKidName()))
                        .setContentIntent(pendingIntent)
                        .setAutoCancel(true)
                        .setFullScreenIntent(pendingIntent,true)
                        .setVisibility(Notification.VISIBILITY_PUBLIC)
                        .build();
                notificationManager.notify(channelId, notification);
            }
            else
            {
                //当sdk版本小于26
                Notification notification = new NotificationCompat.Builder(HomeActivity.this)
                        .setContentText(MessageFormat.format("{0}とはぐれました。至急確認してください！", kidInfoEntity.getKidName()))
                        .setContentIntent(pendingIntent)
                        .setSmallIcon(R.mipmap.parent_app_icon)
                        .setAutoCancel(true)
                        .setFullScreenIntent(pendingIntent,true)
                        .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                        .build();
                notificationManager.notify(channelId, notification);
            }
        }

        // 第三
        MimamoriConfirmDlg mimamoriConfirmDlg = new MimamoriConfirmDlg(
                HomeActivity.this,
                R.style.commonDlg,
                MessageFormat.format(MessageConstants.MSG_MIMAMORI_WARN_3, mKidInfoEntity.getKidName()),
                MessageConstants.MSG_MIMAMORI_WARN_3_CONFIRM,
                MessageConstants.MSG_MIMAMORI_WARN_3_CANCEL,
                mKidInfoEntity.getMacId());
        mimamoriConfirmDlg.show();
        mimamoriConfirmDlg.setOnConfirmSetListener(new MimamoriConfirmDlg.OnConfirmSetListener() {
            @Override
            public void onOperateSet(String pMacId) {
                mimamoriConfirmDlg.dismiss();
                // 継続
                connectDevice(OPEN_MIMAMORI_CONNECTION_BLUETOOTH);
            }
        });
        mimamoriConfirmDlg.setOnCancelSetListener(new MimamoriConfirmDlg.OnCancelSetListener() {
            @Override
            public void onOperateSet(String pMacId) {
                mimamoriConfirmDlg.dismiss();
                mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                mKidInfoEntity.setControlled(false);
                mApp.updateKidInfo(mKidInfoEntity);
                viewDevice(mKidInfoEntity);
            }
        });

        // 第二
        MimamoriPhoneDlg mimamoriPhoneDlg = new MimamoriPhoneDlg(HomeActivity.this,
                R.style.commonDlg,
                MessageFormat.format(MessageConstants.MSG_MIMAMORI_WARN_2, mKidInfoEntity.getKidName()),
                MessageConstants.MSG_MIMAMORI_WARN_2_CONFIRM,
                MessageConstants.MSG_MIMAMORI_WARN_2_CANCEL,
                mKidInfoEntity.getMacId());
        mimamoriPhoneDlg.show();
        mimamoriPhoneDlg.setOnConfirmSetListener(new MimamoriPhoneDlg.OnConfirmSetListener() {
            @Override
            public void onOperateSet(String pMacId) {
                mimamoriPhoneDlg.dismiss();
                KidInfoEntity kidInfoItem = mApp.findKidInfoByMacId(pMacId);
                // 通知音
                if (kidInfoItem.getRingToneSwitch()) {
                    CommonUtils.stopRingtone(HomeActivity.this, kidInfoItem.getRingToneUrl());
                }
                // バイブレーション
                if (kidInfoItem.getShockSwitch()) {
                    CommonUtils.stopVibrator(HomeActivity.this);
                }
                // キッズケータイがかける電話番号
                Intent dialIntent =  new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + kidInfoItem.getKidTel()));
                startActivity(dialIntent);
            }
        });
        mimamoriPhoneDlg.setOnCancelSetListener(new MimamoriPhoneDlg.OnCancelSetListener() {
            @Override
            public void onOperateSet(String pMacId) {
                mimamoriPhoneDlg.dismiss();
                KidInfoEntity kidInfoItem = mApp.findKidInfoByMacId(pMacId);
                // 通知音
                if (kidInfoItem.getRingToneSwitch()) {
                    CommonUtils.stopRingtone(HomeActivity.this, kidInfoItem.getRingToneUrl());
                }
                // バイブレーション
                if (kidInfoItem.getShockSwitch()) {
                    CommonUtils.stopVibrator(HomeActivity.this);
                }
            }
        });
        mimamoriPhoneDlg.setOnImadocoSetListener(new MimamoriPhoneDlg.OnImadocoSetListener() {
            @Override
            public void onOperateSet(String pMacId) {
                mimamoriPhoneDlg.dismiss();
                KidInfoEntity kidInfoItem = mApp.findKidInfoByMacId(pMacId);
                // 通知音
                if (kidInfoItem.getRingToneSwitch()) {
                    CommonUtils.stopRingtone(HomeActivity.this, kidInfoItem.getRingToneUrl());
                }
                // バイブレーション
                if (kidInfoItem.getShockSwitch()) {
                    CommonUtils.stopVibrator(HomeActivity.this);
                }
                Uri uri = Uri.parse("https://imadoco.smt.docomo.ne.jp/location/top_sp");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });

        // 最初の
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (null != bluetoothAdapter && !bluetoothAdapter.isEnabled()) {
            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(
                    HomeActivity.this,
                    R.style.commonDlg,
                    MessageFormat.format(MessageConstants.MSG_MIMAMORI_WARN_1, mKidInfoEntity.getKidName()));
            processWarringDlg.show();
            processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                @Override
                public void onOperateSet() {
                    processWarringDlg.dismiss();
                }
            });
        }
    }
}
